package com.one.square.oauth.config;

import com.one.square.oauth.Strategy.fastjson.FastjsonRedisTokenStoreSerializationStrategy;
import lombok.AllArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import com.one.square.oauth.properties.JwtCAProperties;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.sql.DataSource;
import java.security.KeyPair;

/**
 * @author cwm
 * @Description 鉴权环境准备
 * @date 2021/10/20 下午3:12
 * @Version 1.0
 */
@EnableConfigurationProperties(JwtCAProperties.class)
@AllArgsConstructor
public class AuthorizationEnvironmentConfig {


    private final DataSource dataSource;
    private final RedisConnectionFactory connectionFactory;


    /**
     * 配置jdbc方式客户端服务
     * @return
     */
    @Bean
    public ClientDetailsService clientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 配置token存储方式
     * @param
     * @return
     */
    @Bean
    public TokenStore tokenStore(){
        RedisTokenStore redisTokenStore = new RedisTokenStore(connectionFactory);
        redisTokenStore.setSerializationStrategy(new FastjsonRedisTokenStoreSerializationStrategy());
        return redisTokenStore;
    }

    /**
     * 配置jwt token转换器
     * @return
     */
    @Bean
    @Order(2)
    public JwtAccessTokenConverter jwtAccessTokenConverter(JwtCAProperties jwtCAProperties) {
        final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(keyPair(jwtCAProperties));
        return converter;
    }

    @Bean
    public KeyPair keyPair(JwtCAProperties jwtCAProperties){
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource(jwtCAProperties.getKeyPairName()), jwtCAProperties.getKeyPairSecret().toCharArray());
        return keyStoreKeyFactory.getKeyPair(jwtCAProperties.getKeyPairAlias(), jwtCAProperties.getKeyPairStoreSecret().toCharArray());
    }

}
